/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.hudson.services;

import java.net.URL;
import java.util.Map;
import java.util.HashMap;
import javax.annotation.security.RolesAllowed;
import org.internna.iwebmvc.dao.DAO;
import org.internna.iwebmvc.model.UUID;
import org.internna.iwebmvc.utils.Assert;
import org.internna.iwebjtracker.i18n.MessageResolver;
import org.internna.iwebjtracker.model.DefaultProject;
import org.internna.iwebjtracker.project.validation.Errors;
import org.internna.iwebjtracker.model.DefaultConnectionDetails;
import org.internna.iwebjtracker.hudson.model.HudsonConfiguration;
import org.springframework.context.MessageSource;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

import static org.internna.iwebmvc.utils.StringUtils.hasText;
import static org.internna.iwebjtracker.services.AbstractProjectManager.ROLE_PROJECT_MANAGER;

/**
 * Allows the user to configure a Hudson instance using AJAX.
 *
 * @author Jose Noheda
 * @since 1.0
 */
public final class RemoteHudsonConfigurator extends MessageResolver implements HudsonConfigurator {

    private DAO dao;

    /**
     * Delegates the logic to the super class.
     *
     * @param source any
     */
    public RemoteHudsonConfigurator(MessageSource source) {
        super(source);
    }

    /**
     * Spring injection point (REQUIRED).
     *
     * @param dao a non null instance
     */
    @Required public void setDao(DAO dao) {
        Assert.notNull(dao);
        this.dao = dao;
    }

    /**
     * Saves a Hudson Configuration object in the database.
     *
     * @param project any (if null no operation is performed)
     * @param jobName any (if null no operation is performed)
     * @param details any (if null no operation is performed)
     * @return the i18n translated Error
     */
    @Transactional
    @RolesAllowed(ROLE_PROJECT_MANAGER)
    @Override public String configure(UUID project, UUID connectionDetails, String jobName) {
        if (project != null) {
            if (hasText(jobName)) {
                if (connectionDetails != null) {
                    return checkHudsonServer(project, connectionDetails, jobName);
                }
                return resolve(Errors.NULL_CONNECTION_DETAILS);
            }
            return resolve(HUDSON_MISSING_JOB_NAME);
        }
        return resolve(Errors.NULL_PROJECT_VALIDATION);
    }

    /**
     * Tries to connect to the Hudson server before giving the ok to the validation data.
     *
     * @param project a non null instance
     * @param jobName a non null non empty instance
     * @param connectionDetails a non null instance
     * @return
     */
    protected String checkHudsonServer(UUID project, UUID connectionDetails, String jobName) {
        DefaultConnectionDetails details = dao.find(DefaultConnectionDetails.class, connectionDetails);
        if (details != null) {
            try {
                URL url = new URL(details.getUrl());
                url.openConnection().getContent();
                deletePreviousHudsonConfigurations(project);
                saveConfiguration(project, details, jobName);
                return null;
            } catch (Exception ex) {
                return resolve(HUDSON_NO_RESPONSE_FROM_SERVER);
            }
        }
        return resolve(Errors.NULL_CONNECTION_DETAILS);
    }

    /**
     * Creates a new Hudson configuration object and saves it to the database.
     *
     * @param project a non null instance
     * @param connectionDetails a non null instance
     * @param jobName a non null non empty instance
     * @return null
     */
    protected void saveConfiguration(UUID project, DefaultConnectionDetails connectionDetails, String jobName) {
        HudsonConfiguration sonarConfiguration = new HudsonConfiguration();
        sonarConfiguration.setJobName(jobName);
        sonarConfiguration.setProject(dao.getReference(DefaultProject.class, project));
        sonarConfiguration.setConnectionDetails(connectionDetails);
        dao.create(sonarConfiguration);
    }

    /**
     * Removes all pre-existing Sonar configurations for the given project.
     *
     * @param project a non null instance
     */
    protected void deletePreviousHudsonConfigurations(UUID project) {
        Map<String, Object> params = new HashMap<String, Object>(1);
        params.put("project", project);
        dao.executeUpdate(HudsonConfiguration.DELELETE_HUDSON_CONF_FOR_PROJECT, params);
    }

}
